//jqGrid的配置信息
//
// window.onload = function () {
//     $.jgrid.defaults.width = 1000;
//     $.jgrid.defaults.responsive = true;
//     //$.jgrid.defaults.styleUI = 'Bootstrap';
// }

if ($.jgrid != undefined && $.jgrid.defaults != undefined) {
    $.jgrid.defaults.width = 1000;
    $.jgrid.defaults.responsive = true;
    $.jgrid.defaults.styleUI = 'Bootstrap';
}

// var (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") = "";
//工具集合Tools
window.T = {};

// 获取请求参数
// 使用示例
// location.href = http://localhost:8080/index.html?id=123
// T.p('id') --> 123;
var url = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
};
T.p = url;

//全局配置
$.ajaxSetup({
    dataType: "json",
    cache: false
});

//重写alert
window.alert = function (msg, callback) {
    parent.layer.alert(msg, function (index) {
        parent.layer.close(index);
        if (typeof (callback) === "function") {
            callback("ok");
        }
    });
}

//重写confirm式样框
window.confirm = function (msg, callback) {
    parent.layer.confirm(msg, {btn: ['确定', '取消']},
        function (index) {//确定事件
            if (typeof (callback) === "function") {
                parent.layer.close(index);
                callback("ok");
            }
        });
}


//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        toast("请选择一条记录!", "提示!", "warning");
        return;
    }

    var selectedIDs = grid.getGridParam("selarrrow");
    if (selectedIDs.length > 1) {
        toast("请选择一条记录!", "提示!", "warning");
        return;
    }

    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        //alert("请选择一条记录");
        toast("请选择一条记录!", "提示!", "warning");
        return;
    }

    return grid.getGridParam("selarrrow");
}

//判断是否为空
function isBlank(value) {
    return !value || !/\S/.test(value)
}

/**
 * js通过location.search来获取页面传来的参数
 * @param name 参数名
 * @returns {*}
 */
function getParams(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return (r[2]);
    return null;
}

/**
 * 获取字典表中的值
 * @param dicType
 * @param nodeId
 */
function selectFromDicByType(dicType, nodeId) {

    var url = "sys/dict/listByType/" + dicType;
    var $userType = $("#" + nodeId);
    $userType.empty();
    $.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + url, function (r) {
        $.each(r.list, function (item, obj) {
            var $option = $("<option value='" + obj.code + "'>" + obj.value + "</option>");
            $userType.append($option);
        });
    });
}

/**
 * @Author: JuiceYan
 * @Description: select 下拉框
 * @param:
 * @return:
 * @throws:
 * @Date: 11:39 2018/12/28
 */
function selectOptions(selectUrl, ruleId) {
    $.getJSON(selectUrl, function (r1) {
        var $select = $("#" + ruleId);
        var r = r1.page.list;
        if (r) {
            $.each(r, function (item, obj) {
                var $option = $("<option value='" + obj.id + "'>" + obj.name + "</option>")
                $select.append($option);
            });

        }
    });
}

/**
 * @Author: JuiceYan
 * @Description: select 选项加载
 * @param:
 * @return:
 * @throws:
 * @Date: 18:08 2018/12/27
 */
function getJqgridOptionValues(url) {
    var options = "";
    var i = 0;
    $.ajax({
        async: false,  //千万要记住加这个属性配置
        type: "post",
        url: url,
        success: function (data1) {
            var data = data1.page.list;
            for (i; i < data.length; i++) {
                if (i != data.length - 1) {
                    options += data[i].id + ":" + data[i].name + ";";
                } else {
                    options += data[i].id + ":" + data[i].name;
                }
            }
        }
    });
    return options;
}

function getJqgridOptionValuesByDic(dicType) {
    // var url = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"")+"sys/dict/listByType/" + dicType;
    var url = "/sys/dict/listByType/" + dicType;
    var options = "";
    var i = 0;
    $.ajax({
        async: false,  //千万要记住加这个属性配置
        type: "post",
        url: url,
        success: function (data1) {
            var data = data1.list;
            for (i; i < data.length; i++) {
                if (i != data.length - 1) {
                    options += data[i].code + ":" + data[i].value + ";";
                } else {
                    options += data[i].code + ":" + data[i].value;
                }
            }
        }
    });
    return options;
}

function selectFromDicByType(dicType, nodeId) {
    var url = "sys/dict/listByType/" + dicType;
    var $userType = $("#" + nodeId);
    $userType.empty();
    $.get((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + url, function (r) {
        $.each(r.list, function (item, obj) {
            var $option = $("<option value='" + obj.code + "'>" + obj.value + "</option>");
            $userType.append($option);
        });
    });
}

/**
 * @Author: JuiceYan
 * @Description: select 下拉框
 * @param:
 * @return:
 * @throws:
 * @Date: 11:39 2018/12/28
 */
function selectOptions(selectUrl, ruleId) {
    $.getJSON(selectUrl, function (r1) {
        var $select = $("#" + ruleId);
        var r = r1.page.list;
        if (r) {
            $.each(r, function (item, obj) {
                var $option = $("<option value='" + obj.id + "'>" + obj.name + "</option>")
                $select.append($option);
            });

        }
    });
}

/**
 * @Author: JuiceYan
 * @Description: select 选项加载
 * @param:
 * @return:
 * @throws:
 * @Date: 18:08 2018/12/27
 */
function getJqgridOptionValues(url) {
    var options = "";
    var i = 0;
    $.ajax({
        async: false,  //千万要记住加这个属性配置
        type: "post",
        url: url,
        success: function (data1) {
            var data = data1.page.list;
            for (i; i < data.length; i++) {
                if (i != data.length - 1) {
                    options += data[i].id + ":" + data[i].name + ";";
                } else {
                    options += data[i].id + ":" + data[i].name;
                }
            }
        }
    });
    return options;
}

/**
 * @Author: JuiceYan
 * @Description: 导出excel
 * @param:
 * @return:
 * @throws:
 * @Date: 16:58 2018/9/26
 */
function exportExcel(prefix, params) {
    if (com.isNull(params)) {
        params = "";
    }

    window.location.href = prefix + "/exportExcel" + params;
}

/**
 * @Author: JuiceYan
 * @Description: 导出excel模板
 * @param:
 * @return:
 * @throws:
 * @Date: 17:09 2018/12/31
 */
function exportExcelTemplate(prefix, params) {
    if (com.isNull(params)) {
        params = "";
    }
    let newUrl = prefix + "/template" + params;
    window.location.href = newUrl;
    $('#excelModal').modal('hide');
}

/**
 * @Author: JuiceYan
 * @Description: 打开上传文件模态框
 * @param:
 * @return:
 * @throws:
 * @Date: 17:38 2018/12/31
 */
function openImportExcel() {
    //清空原来的文件名
    $('#photoCover').val('');
    $('#excelModal').modal('show');
}

/**
 * @Author: JuiceYan
 * @Description: 导入excel
 * @param:
 * @return:
 * @throws:
 * @Date: 16:59 2018/9/26
 */
function importExcel(prefix, params, vm) {
    if (com.isNull(params)) {
        params = "";
    }
    let excelFileName = $("#excelFile").val(); // js 获取文件对象
    if (com.isNull(excelFileName)) {
        toast('请选择文件！');
        return;
    }
    //此种方式无效直接用form dom new FormData
    // let formFile = new FormData($("#importForm"));
    let formFile = new FormData();
    let excel = $('input[id=excelFile]')[0].files[0];
    formFile.append("file", excel);
    let excelUrl = prefix + "/importExcel" + params;
    com.AjaxPostFile(excelUrl, formFile, function (r) {
        if (r.success) {
            if (!com.isNull(r.msg)) {
                toast(r.msg);
            } else {
                toast('操作成功');
            }
            $('#excelModal').modal('hide');
            vm.reload();
        } else {
            warning(r.msg);
        }
    });

    // top.layer.open({
    //     type: 1,
    //     area: ['50%', '50%'],
    //     title: "导入数据",
    //     content: $("#importBox").html(),
    //     btn: ['下载模板', '确定', '关闭'],
    //     btn1: function (index, layero) {
    //         var newUrl = prefix + "/template" + params;
    //
    //         window.location.href = newUrl;
    //     },
    //     btn2: function (index, layero) {
    //         var inputForm = top.$("#importForm");
    //         ;
    //         inputForm.attr('action', prefix + "/importExcel");
    //         // inputForm.attr('enctype',"multipart/form-data");
    //         // var top_iframe = getActiveTab().attr("name");//获取当前active的tab的iframe
    //         // inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
    //         top.$("#importForm").submit();
    //
    //         console.log(inputForm);
    //         // var form = new FormData(inputForm);
    //         // $.ajax({
    //         //     url: prefix+"/importExcel",
    //         //     type:"post",
    //         //     data:form,
    //         //     processData:false,
    //         //     contentType:false,
    //         //     success:function(data){
    //         //         console.log(data);
    //         //         if (data.success){
    //         //             alert("成功！");
    //         //         }else {
    //         //             alert("错误！！");
    //         //         }
    //         //     },
    //         //     error:function(e){
    //         //         alert("错误！！");
    //         //     }
    //         // });
    //
    //         // inputForm.ajaxSubmit({
    //         //     success:function(data){
    //         //         console.log(data);
    //         //         if (data.success){
    //         //             alert("成功！");
    //         //         }else {
    //         //             alert("错误！！");
    //         //         }
    //         //     }
    //         // });
    //         top.layer.close(index);
    //     },
    //
    //     btn3: function (index) {
    //         top.layer.close(index);
    //     }
    // });
}

//
// function openDomView(domId, url) {
//     top.layer.open({
//         type: 1,
//         area: ['50%', '50%'],
//         title: "导入数据",
//         content: $("#" + domId + "Box").html(),
//         btn: ['确定', '关闭'],
//         btn1: function (index, layero) {
//             var inputForm = top.$("#" + domId + "Form");
//             inputForm.attr('action', url);
//             inputForm.submit();
//             console.log(inputForm);
//             top.layer.close(index);
//         },
//         btn2: function (index) {
//             top.layer.close(index);
//         }
//     });
// }

function getActiveTab() {
    return $(".J_iframe:visible");
}

/**
 * 打开对话框
 * @Author
 * @param title 标日
 * @param url 跳转页面
 * @param width 宽度
 * @param height 长度
 * @param target
 */
function openDialog(title, url, width, height, target) {

    if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {//如果是移动端，就使用自适应大小弹窗
        width = 'auto';
        height = 'auto';
    } else {//如果是PC端，根据用户设置的width和height显示。

    }

    top.layer.open({
        type: 2,
        area: [width, height],
        title: title,
        maxmin: true, //开启最大化最小化按钮
        content: url,
        btn: ['确定', '关闭'],
        yes: function (index, layero) {
            var body = top.layer.getChildFrame('body', index);
            var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var inputForm = body.find('#inputForm');
            top.iframe1 = top.document.getElementById($(iframeWin).attr('id'));

            var top_iframe;
            if (target) {
                top_iframe = target;//如果指定了iframe，则在iframe中跳转
            } else {
                top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe
            }
            inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
            if (/iframe/.test($(inputForm).attr('data-tag'))) {
                top.layerIndex = index;
                messenger.addTarget(iframeWin.contentWindow, 'iframe1');
                messenger.targets['iframe1'].send($(iframeWin).attr('id'));

            } else {
                if (iframeWin.contentWindow.doSubmit()) {
                    // top.layer.close(index);//关闭对话框。
                    setTimeout(function () {
                        top.layer.close(index)
                    }, 1);//延时0.1秒，对应360 7.1版本bug
                }
            }


        },
        cancel: function (index) {
            console.log(index)
        }
    });
}

/**
 * 打开对话框(查看)
 * @Author
 * @param title 标日
 * @param url 跳转页面
 * @param width 宽度
 * @param height 长度
 * @param target
 */

function openDialogView(title, url, width, height) {

    if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {//如果是移动端，就使用自适应大小弹窗
        width = 'auto';
        height = 'auto';
    } else {//如果是PC端，根据用户设置的width和height显示。

    }
    top.layer.open({
        type: 2,
        area: [width, height],
        title: title,
        maxmin: true, //开启最大化最小化按钮
        content: url,
        btn: ['关闭'],
        cancel: function (index) {
        }
    });

}

/**
 * 模块名：共通脚本
 * 程序名: 通用方法common.js
 **/

var com = {};
com.vm = {};

/* 常用表单提交 */
com.contentTypeUrlencoded = "application/x-www-form-urlencoded";
com.contentTypeFormData = "multipart/form-data";

/**
 * @author
 * @constructor AjaxPost
 * @description 通用ajax 无进度条
 * @example com.AjaxPost("a.do","type=1","json",acallback);
 * @since version 1.0
 * @param url ajax访问url
 * @param param ajax参数
 * @param dataType 数据类型
 * @param callback 回调函数
 */
com.AjaxPost = function (url, param, dataType, callback, contentType) {
    jQuery.ajax({
        type: "post",
        url: url,
        data: param,
        contentType: contentType == null ? "application/json" : contentType,
        dataType: dataType,
        success: callback,
        error: function (e) {
            var msg = e.responseText;
            toast("Ajax请求异常!" + msg, "请求提示", "error");
            //com.msg("Ajax错误提示!"+msg,false);
        }
    });
};

com.AjaxPostFile = function (url, param, callback) {
    jQuery.ajax({
        type: "post",
        url: url,
        data: param,
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false, //必须,
        dataType: "json",
        success: callback,
        error: function (e) {
            var msg = e.responseText;
            toast("Ajax请求异常!" + msg, "请求提示", "error");
            //com.msg("Ajax错误提示!"+msg,false);
        }
    });
};


/**
 * @author
 * @constructor AjaxGet
 * @description 通用ajax 无进度条
 * @example com.AjaxGet("a.do","type=1","json",acallback);
 * @since version 1.0
 * @param url ajax访问url
 * @param param ajax参数
 * @param dataType 数据类型
 * @param callback 回调函数
 */
com.AjaxGet = function (url, param, dataType, callback, contentType, isAsync) {
    // axios.get(url)
    //     .then(response => this.excel = response.data.entity
    //     )
    //     .catch(function (error) {
    //         console.log(error);
    //     });

    jQuery.ajax({
        type: "get",
        url: url,
        data: param,
        contentType: contentType == null ? "application/json" : contentType,
        dataType: dataType == null ? "json" : dataType,
        success: callback,
        async: isAsync == null ? true : isAsync,
        error: function (e) {
            var msg = e.responseText;
            var ret = msg
                .match(/^{\"Message\":\"(.*)\",\"ExceptionMessage\":\"(.*)\",\"ExceptionType\":.*/);
            if (ret != null) {
                msg = (ret[1] + ret[2]).replace(/\\"/g, '"').replace(
                    /\\r\\n/g, '<br/>').replace(/dbo\./g, '');
            } else {
                try {
                    msg = $(msg).text() || msg;
                } catch (ex) {
                }
            }

            toast("Ajax请求异常!" + msg, "请求提示", "error");

            //alert("Ajax请求异常!"+msg);
            //com.msg("Ajax错误提示!"+msg,false);
        }
    });
};

/**
 * @author
 * @constructor isNull
 * @description 判断是否为空
 * @example isNull("aa");
 * @param exp 判断的值
 * @return true为空，false不为空
 */
com.isNull = function (exp) {
    if (exp == null || typeof (exp) == "undefined" || exp == '' || jQuery.trim()) {
        return true;
    }
    return false;
}

/**
 * @author zhongyuan
 * @constructor randomNum
 * @description 随机生成几位随机数
 * @example randomNum("abc",5);
 * @param 生成5位随机数
 * @return 返回一个前缀+随机数的字符串
 */
com.randomNum = function (pre, num) {
    var pre = pre;
    var num = num;
    var number = '';
    if (pre == '' || pre == undefined || pre == null) {
        pre = "";
    }
    if (num == '' || num == undefined || num == null) {
        num = 1;
    }
    for (var i = 0; i < num; i++) {
        number += parseInt(Math.random() * 10);
    }
    return pre + number;
}


com.layer = function () {
    try {
        if (top.layer) {
            return top.layer
        }
        if (parent.parent.layer) {
            return parent.parent.layer
        }
        if (parent.layer) {
            return parent.layer
        }
    } catch (e) {
    }
    if (window.layer) {
        return layer
    }
    return null
}

function warning(msg) {
    toast(msg, "提示!", "warning");
}

/**
 * @author
 * @constructor toast
 * @description 消息提示
 * @example toast("消息内容","消息标题");
 * @param msg 消息内容
 * @param title 消息标题
 * @param type 消息类型
 */
function toast(msg, title, type) {
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "positionClass": "toast-top-right",
        "onclick": null
    }
    type = com.isNull(type) ? "success" : type;
    title = com.isNull(title) ? "提示！" : title;
    msg = com.isNull(msg) ? "操作成功！" : msg;

    if (type == "success") {
        toastr.success(msg, title);
    } else if (type == "warning") {
        toastr.warning(msg, title);
    } else if (type == "error") {
        toastr.error(msg, title);
    } else {
        toastr.info(msg, title);
    }
}

/**
 * @Author: JuiceYan
 * @Description: 自动生成最新sort排序
 * @param:
 * @return:
 * @throws:
 * @Date: 17:02 2018/9/30
 */
function generateSort(sort) {
    var newSort = 1;
    //返回数据表的ID数组["66","39"..]
    var ids = $('#jqGrid').getDataIDs();
    var len = ids.length;
    for (var i = 0; i < len; i++) {
        //获取当前的数据行
        var getRow = $('#jqGrid').getRowData(ids[i]);
        var oldSort = getRow[sort];
        if (oldSort >= newSort) {
            newSort = parseInt(oldSort) + 10;
        }
    }
    return newSort;
}

function getSystemParams() {
    $.ajaxSettings.async = false;
    var systemParams
    $.getJSON((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "sys/config/get/sys?_" + $.now(),
        function (r) {
            console.log("systemParams", r)
            if (!com.isNull(r.data)) {
                systemParams = r.data;
            }
        });
    $.ajaxSettings.async = true;
    console.log("systemParams", systemParams)

    if (!com.isNull(systemParams)) {
        var sys = JSON.parse(systemParams);
        //    获取系统标题
        var systemTitle = sys["systemTitle"];
        var copyright = sys["copyright"];

        $('.systemTitle').html(systemTitle);
        $('.copyright').html(copyright);
    }
    return systemParams
}


// 回显数据字典
com.selectDictLabel = function (datas, value) {

    var actions = [];
    $.each(datas, function (index, dict) {
        if (dict.value == value || dict.value == value + '') {
            actions.push("<span class='label label-" + dict.listClass + "'>" + dict.name + "</span>");
            return false;
        }
    });
    return actions.join('');
}

// 获取字典数据
com.selectDictDatas = function (type) {
    let url = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "anon/productionqr/type/" + type;
    let datas = []
    com.AjaxGet(url, null, "json", function (r) {
        if (r.success) {
            datas = r.data
        } else {
            toastr.error(r.msg, "获取字典数据");
        }
    }, null, false)
    return datas
}

//获取文件后缀
com.checkFileType = function(filename, tarType){
    let index1=filename.lastIndexOf(".");
    let index2=filename.length;
    let type=filename.substring(index1+1,index2);
    return tarType.indexOf(type.toLowerCase()) != -1;
}


/**
 * @Author: JuiceYan
 * @Description: 表单文件上传
 * @param:
 * @return:
 * @throws:
 * @Date: 17:04 2019/3/8
 */
com.uploadMyFile = function (url, vm, fileDomId, obj) {
    let formFile = new FormData();

    let fileName = $("#" + fileDomId + "").val(); // js 获取文件对象
    if (!com.isNull(fileName)) {
        // toast('请选择文件！');
        let file = $('input[id=' + fileDomId + ']')[0].files[0];
        formFile.append("file", file);
        // return;
    }
    for (var key in obj) {
        if (key != 'url' && obj[key] !== null) {
            formFile.append(key, obj[key]);
        }
    }

    com.AjaxPostFile(url, formFile, function (r) {
        if (r.success) {
            if (!com.isNull(r.msg)) {
                toast(r.msg);
            } else {
                toast('操作成功');
            }
            $('#excelModal').modal('hide');
            vm.reload();
        } else {
            warning(r.msg);
        }
    });
    $("#url").val("");  //清空缓存
}

/**
 * @Author: JuiceYan
 * @Description: 单文件上传
 * @param:
 * @return:
 * @throws:
 * @Date: 17:04 2019/3/8
 */
com.simpleUploadMyFile = function (attributeIndex,vm,url=(window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"")+"api/static/file/baseInfo") {

    let fileName = $("#attribute" + attributeIndex + "").val(); // js 获取文件对象

    let attribute = vm.allAttributes[attributeIndex];
    let tarType=[]
    switch (attribute.type) {
        case 5:
            tarType = ["jpg", "png"];
            if (!com.checkFileType(fileName, tarType)) {
                warning('只能上传 ' + tarType.join(",") + ' 文件！')
                return
            }
            break;
        case 6:
            tarType = ["mp4"];
            if (!com.checkFileType(fileName, tarType)) {
                warning('只能上传 ' + tarType.join(",") + ' 文件！')
                return
            }
            break;
    }
    let formFile = new FormData();
    if (!com.isNull(fileName)) {
        // toast('请选择文件！');
        let file = $('input[id=attribute' + attributeIndex + ']')[0].files[0];
        formFile.append("file", file);
        // return;
    }
        let index=layer.msg("文件上传中...", {
            icon: 16,
            time : false,
            shade: 0.01
        });
    com.AjaxPostFile(url, formFile, function (r) {
        layer.close(index);
        if (r.success) {
            if (!com.isNull(r.msg)) {
                toast(r.msg);
            } else {
                toast('操作成功');
            }
            attribute.defaultValue = r.data

        } else {
            warning(r.msg);
        }
    });
    // 清空文件缓存
    $("input[type=file]").val("");
}


layui.use(['layer'], function(){
    var layer = layui.layer
});